package com.pkk.penguin.uti.oss.support;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.pkk.components.util.util.StringHelper;
import com.pkk.penguin.uti.oss.config.OssClientConfig;
import com.pkk.penguin.uti.oss.config.OssConfig;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @description: oss的支持
 * @author: peikunkun
 * @create: 2019-11-08 11:56
 **/
@Slf4j
public class PenguinOssSupport {


  /**
   * @Description: 上传文件到腾讯oss
   * @Param: [file, objectMetadata]
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2018/9/16 0016 下午 5:57
   */
  public static String uploadToTCOss(Object file, String parent, ObjectMetadata objectMetadata, String fileType) {
    InputStream inputStream = null;
    if (file instanceof String) {
      try {
        inputStream = new FileInputStream((String) file);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("获取文件失败:" + e.getStackTrace());
        return null;
      }
    } else if (file instanceof InputStream) {
      if (objectMetadata == null) {
        return null;
      }
      inputStream = (InputStream) file;
    }
    if (inputStream == null) {
      return null;
    }

    try {
      objectMetadata.setContentLength(inputStream.available());
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println();
      log.error("获取文件失败:" + e.getStackTrace());
      return null;
    }

    // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
    // 大文件上传请参照 API 文档高级 API 上传
    // 指定要上传到 COS 上对象键
    // 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中，对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
    String key = "";
    final String fileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN).concat(fileType);
    if (StringUtils.isNotBlank(parent)) {
      key = parent + "/" + fileName;
    } else {
      key = fileName;
    }
    PutObjectRequest putObjectRequest = new PutObjectRequest(OssConfig.BUCKETNAME, key, inputStream, objectMetadata);
    PutObjectResult putObjectResult = OssClientConfig.cosclient.putObject(putObjectRequest);
    OssClientConfig.cosclient.shutdown();
    log.info("文件上传操作:{}", JSONObject.toJSONString(putObjectResult));
    return "https://fine-1257290547.cos.ap-hongkong.myqcloud.com/" + key;
  }
}
